<template>
  <div class="Search-contanier">
    <!-- 搜索栏 -->
    <form class="searchFrom" action="/">
      <van-search v-model="searchText" show-action shape="round" background="#3296fa" placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" @focus="isResult = false" />
    </form>

    <!-- 搜索结果 -->
    <SearchResult v-if="isResult" :searchText="searchText"></SearchResult>
    <!-- 联想建议 -->
    <SearchSuggestion @search="onSearch" v-else-if="searchText" :searchText="searchText"></SearchSuggestion>
    <!-- 搜索历史记录 -->
    <SearchHistory v-else :SearchHistories="SearchHistories" @clear-SearchHistory="SearchHistories = []" @search="onSearch"></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import SearchResult from './components/SearchResult.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'SearchIndex',
  data() {
    return {
      searchText: '',
      isResult: false, // 控制搜索结果是否展示
      SearchHistories: getItem('TOUTIAO_SEARCH_HISTORY') || [] // 存储搜索历史记录
    }
  },
  watch: {
    SearchHistories(val) {
      setItem('TOUTIAO_SEARCH_HISTORY', val)
      // console.log('shsh')
    }
  },
  methods: {
    // 按下回车时候确认搜索后的操作
    onSearch(val) {
      // Toast(val)
      // 更新文本框内容
      this.searchText = val
      // 储存历史搜索记录
      const index = this.SearchHistories.indexOf(val)
      if (index !== -1) {
        this.SearchHistories.splice(index, 1)
      }

      this.SearchHistories.unshift(val)
      // 渲染搜索结果
    },
    onCancel() {
      // Toast('取消')
      this.$router.back()
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  }
}
</script>

<style lang="less" scoped>
.Search-contanier {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .searchFrom {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 1;
  }
}
</style>
